package com.bootdo.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.configure.controller.BaseController;
import com.bootdo.common.configure.domain.Tree;
import com.bootdo.common.configure.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RandomValidateCodeUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.common.utils.google.GoogleAuthenticator;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MenuService;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.UserService;

@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    @GetMapping({"/", ""})
    String welcome(Model model) {
//        return "login";
        return "redirect:/login";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model, String secret) {
        model.addAttribute("userId", getUserId());
        if (StringUtils.isBlank(secret) && 1 != getUserId()){
            //生成密钥
            secret = GoogleAuthenticator.generateSecretKey();
            String userName = getUser().getUsername();
            //生成二维码
            String code = GoogleAuthenticator.getQRBarcode(userName, secret);
            model.addAttribute("code", code);
            model.addAttribute("secret", secret);
            return "tips";
        } else {
            List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
            List<RoleDO> roles = roleService.list(getUserId());
            for (RoleDO role : roles){
                if ("true".equals(role.getRoleSign())) {
                    model.addAttribute("role", role.getRoleName());
                    model.addAttribute("roleId", role.getRoleId());
                    break;
                }
            }
            model.addAttribute("menus", menus);
            model.addAttribute("name", getUser().getName());
            model.addAttribute("username", getUsername());
            if (StringUtils.isBlank(secret)){
                model.addAttribute("secret", getUser().getSecret());
            } else {
                model.addAttribute("secret", secret);
            }
            return "index_v1";
        }
    }

    @GetMapping("/login")
    String login(Model model) {
        return "login";
    }

    /**
     * 生成密钥
     * @param username
     * @param password
     * @param verify
     * @param request
     * @return
     */
    @Log("登录")
    @ResponseBody
    @PostMapping("/login")
    R ajaxLogin(String username, String password,String verify,String code,String secrets,HttpServletRequest request) {

        try {
            //从session中获取随机数
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码");
            }
            if (random.equals(verify)) {
            } else {
                return R.error("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return R.error("验证码校验失败");
        }

        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //验证密钥
            if("0".equals(secrets)){
                boolean f = GoogleAuthenticator.checkCode(getUser().getSecret(), code);
                if (f){
                    return R.ok();
                } else {
                    subject.logout();
                    return R.error("用户手机令牌错误");
                }
            }
            return R.ok();
        } catch (AuthenticationException e) {
            logger.error("<==========用户登录错误========>" + e);
            return R.error("用户或密码错误");
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main(Model model, String secret) {
        if (StringUtils.isBlank(secret)){
            //生成密钥
            secret = GoogleAuthenticator.generateSecretKey();
            String userName = getUser().getUsername();
            //生成二维码
            String code = GoogleAuthenticator.getQRBarcode(userName, secret);
            model.addAttribute("code", code);
            model.addAttribute("secret", secret);
            model.addAttribute("userId", getUserId());
            return "tips";
        } else {
            model.addAttribute("roleId", getUser().getRoleIds().get(0));
            return "orders/profit/list";
        }
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            //输出验证码图片方法
            randomValidateCode.getRandcode(request, response);
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }

    /**
     * 获取用户是否存在Google密钥
     */
    @GetMapping(value = "/getSecret")
    @ResponseBody
    public R getSecret(Model model, String username, String password){
        String secret = "";
        password = MD5Utils.encrypt(username, password);
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        map.put("password", password);
        List<UserDO> list = userService.list(map);
        if (list.size() <= 0) {
            return R.error();
        }
        if (list.size() > 0) {
            UserDO userDO = list.get(0);
            if (StringUtils.isBlank(userDO.getSecret())){
                return R.error();
            } else {
                secret = userDO.getSecret();
            }
        }
        return R.ok(secret);
    }

    /**
     * 获取用户是否存在Google密钥
     */
    @Log("保存密钥")
    @PostMapping(value = "/saveSecret")
    @ResponseBody
    public R saveSecret(String code, String secret, String userId){
        boolean f = GoogleAuthenticator.checkCode(secret, code);
        if (f){
            UserDO userDO = new UserDO();
            userDO.setUserId(Long.valueOf(userId));
            userDO.setSecret(secret);
            int count = userService.updateSecret(userDO);
            if (count <= 0){
                logger.error("数字令牌密钥保存失败");
            }
            return R.ok();
        } else {
            logger.error("数字令牌输入有误");
            return R.error("数字令牌输入有误");
        }
    }

}
